import { 
    OutputFactory, OutputCfg, OutputType, 
    Finder, Loader, 
    ArkSerializer, ArkNodeTracePath,
    Log
} from '@meminsight/core';

const DOMAIN: string = 'exampletools';
const TAG: string = 'memtest';

const args = process.argv.slice();
const type = args.length > 2 ? Number(args[2]) : 0;
const count = args.length > 3 ? Number(args[3]) : 5;
const nodeName = args.length > 4 ? args[4] : '';
const filepath = args.length > 5 ? args[5] : '';

function error(msg: string) {
    Log.error(DOMAIN, TAG, msg);
}

function info(msg: string) {
    Log.info(DOMAIN, TAG, msg);
}

(async function () {
    if (filepath === '') {
        error('filepath is empty.');
        return;
    }
    const snapshot = await Loader.loadFromFile(filepath);

    if (type === 0) {
        const nodes = Finder.findNodesByNameCount(snapshot, nodeName, count);
        const cfg: OutputCfg = {
            desc: '',
            output: {
                dir: '',
                filename: '',
                extension: OutputType.CONSOLE.toString(),
            },  
            node: {
                enableId: true,
                enableType: true,
                enableName: true,
                enableSelfSize: false,
                enableRetainedSize: false,
            }
        };
        let nodeData = ArkSerializer.getConsoleDataByNodes(true, nodes, cfg);
        OutputFactory.getOutput(OutputType.CONSOLE).output(nodeData, cfg);
    } else {
        const nodes = Finder.findNodesByNameCount(snapshot, nodeName, count);
        const shortestPaths = Finder.findShortestPaths(snapshot, nodes);
        let set = new Set<number>();
        shortestPaths.forEach(item => {
            if (item) {
                let tracePath = new ArkNodeTracePath(item, true);
                let pathStr = tracePath.getTracePathInfo();
                console.log(pathStr);
                console.log('\n');
            }
        });
    }
})();
